// Learn cc.Class:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/class.html
//  - [English] http://www.cocos2d-x.org/docs/creator/en/scripting/class.html
// Learn Attribute:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/reference/attributes.html
//  - [English] http://www.cocos2d-x.org/docs/creator/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/life-cycle-callbacks.html
//  - [English] http://www.cocos2d-x.org/docs/creator/en/scripting/life-cycle-callbacks.html

cc.Class({
    extends: cc.Component,

    properties: {
        background:cc.Node,
        box:cc.Prefab,
        colorBoxs:[cc.SpriteFrame],
        gameStar :cc.Prefab,
        colorStar:[cc.SpriteFrame],
        scoreLab:cc.Label,
        resultLabel:cc.Label,
        resultNode:cc.Node,
    },

    // LIFE-CYCLE CALLBACKS:

     onLoad () {
         //设置背景图高度和屏幕高度一样
        this.size = cc.winSize;
        this.background.height = this.size.height;
        this.dataArray = [];
        this.isxiaochuzhong = false;
        this.targetScore = 0;
        this.counter = 0;
         //加载背景音乐
         cc.loader.loadRes('/music/music', cc.AudioClip, function (err, clip) {

            cc.audioEngine.playMusic(clip, true);
            cc.audioEngine.setMusicVolume(1);
        });

        cc.loader.loadRes('/music/pop', cc.AudioClip, function (err, clip) {
            this.pop = clip;
        }.bind(this));
        cc.loader.loadRes('/music/good', cc.AudioClip, function (err, clip) {
            this.goodMusic = clip;
        }.bind(this));
        cc.loader.loadRes('/music/great', cc.AudioClip, function (err, clip) {
            this.greatMusic = clip;
        }.bind(this));
    },

    start () {
         this.initData();
    },
    initData(){
        this.dataArray = [];
        this.isxiaochuzhong = false;
        this.targetScore = 0;
        this.counter = 0;
        var width = this.size.width/10;
        for(var i=0;i<10;i++)
        {
            for(var j=0;j<10;j++)
            {
                var box = cc.instantiate(this.box);
                box.position = cc.v2(0,0);
                box.setScale(0.1,0.1);
                this.background.addChild(box);
                var act = cc.moveTo(0.7, cc.v2((2*j-9) * width/2, width * i - this.size.height/3.5));
                var act2 = cc.scaleTo(0.7,1,1);
                box.runAction(cc.spawn(act,act2));
                box.xx = j;
                box.yy = i;
                var k = Math.floor(Math.random()*10000)%5;
                var color = "";
                switch (k)
                {
                    case 0: color = "blue";break;
                    case 1: color = "green";break;
                    case 2: color =  "pink";break;
                    case 3: color =  "purple";break;
                    case 4: color =  "yellow";break;
                    default :
                        color =  "error color !"
                }
                box.skinColor = color;
                box.getComponent(cc.Sprite).spriteFrame = this.colorBoxs[k];   
                this.dataArray.push(box);
            }
        }
        cc.loader.loadRes('/music/readygo', cc.AudioClip, function (err, clip) {
            cc.audioEngine.play(clip,false,1);
        }.bind(this));
    },

  
    getCurrentScore(n){
        var score = 0;
        if(n<=7) score = Math.pow(2,n);
        else  score = 25 * Math.pow(n,2) - 275 * n + 828;
        
        var getScoreLab = new cc.Node('getScoreLab');
        const label = getScoreLab.addComponent(cc.Label);
        label.string = "" + score;
        label.fontSize = 60;
        label.lineHeight = 60;
        getScoreLab.position = cc.v2(60,200);
        getScoreLab.width = 200;
        getScoreLab.height = 80;
        this.background.addChild(getScoreLab);
        var seq = cc.sequence(cc.moveTo(0.8,cc.v2(60,400)),cc.removeSelf());
        getScoreLab.runAction(seq);
        return score + parseInt(this.scoreLab.string);
    },

    /*点击开始消除 */
    itemBoxClicked(box){
        if(this.isxiaochuzhong) return;
        this.selectColorBoxs = [box];
        this.bianliArray = [box];
        this.getAround(this.bianliArray);
        console.log(this.selectColorBoxs);
        if(this.selectColorBoxs.length>1){
            this.targetScore = this.getCurrentScore(this.selectColorBoxs.length);
            this.addCount = Math.ceil((this.targetScore - parseInt(this.scoreLab.string))/20);
            if(this.selectColorBoxs.length>8)
            {
                cc.audioEngine.play(this.greatMusic,false,1);
            }
            else
            {
                if(this.selectColorBoxs.length>=6)
                {
                    cc.audioEngine.play(this.goodMusic,false,1);
                }
            }
            this.isxiaochuzhong = true;
            this.startBoxAction();
        }
    },
    /* 获取所有和点击颜色一样 连在一起box */
    getAround(arr){
        var nextSearchArray = [];
        for(var j = 0; j< arr.length;j++)
        {
            var itemBox = arr[j];
            var array = [{yy :itemBox.yy,   xx:itemBox.xx-1,skinColor:itemBox.skinColor},
                         {yy :itemBox.yy,   xx:itemBox.xx+1,skinColor:itemBox.skinColor},
                         {yy :itemBox.yy-1,xx:itemBox.xx,skinColor:itemBox.skinColor},
                         {yy :itemBox.yy+1, xx:itemBox.xx,skinColor:itemBox.skinColor}];

            for(var i=0;i<array.length;i++){
                var isBox = this.isExistBox(array[i]);
                if(isBox && !this.isContainBox(isBox))
                {
                   this.selectColorBoxs.push(isBox);
                   nextSearchArray.push(isBox);
                }
            }
        }
        if(nextSearchArray.length >0){
            this.getAround(nextSearchArray);
        }
    },
     /* 是否存在 对应id的方块 */
     isExistBox(box){
        if(box.yy<0 || box.yy>9) return false;
        if(box.xx<0 || box.xx>9) return false;
        for (var i=0;i<this.dataArray.length;i++)
        {
            var item = this.dataArray[i];
            if (item == null) continue;
            if(item.yy == box.yy && item.xx == box.xx && item.skinColor == box.skinColor)
            {
                return item;
            }
        }
        return false;
    },
    /* 选中项中是否包含当前参数项 */
    isContainBox(box){
        for(var i=0;i<this.selectColorBoxs.length;i++){
            var item = this.selectColorBoxs[i];
            if(item.yy == box.yy && item.xx == box.xx)
            {
                return true;
            }
        }
        return false;
    },

    /* box 的移动、删除 动作*/
    startBoxAction(){
       
        //控制下落 逻辑
        var x_array = [];
        for(var j=0;j<this.selectColorBoxs.length;j++)
        {
            var item = this.selectColorBoxs[j];
            var flag = false;
            for(var i=0;i<x_array.length;i++)
            {
                var itemx = x_array[i];
                if(itemx == item.xx){
                    flag = true;
                    break;
                }
            }
            if(flag==false)
                x_array.push(item.xx);
        }
        console.log(x_array);
        var moveArr = [];//需要移动的box
        var  h = 0;
        for(var i = 0;i<this.dataArray.length;i++)
        {
            var box = this.dataArray[i];
            if(box == null) continue;

            this.getActionInfos(box,x_array);

            var obj = this.getActionInfos(box,x_array);
            if(obj.flag == "destory")
            {
                ++h;
                this.dataArray[i].runAction(cc.sequence(cc.delayTime(0.1*h),cc.callFunc(function (target,data) {
                    for(var z=0;z<4;z++){
                        var star = cc.instantiate(this.gameStar);
                        star.position = this.dataArray[data.data].position;
                        star.getComponent(cc.Sprite).spriteFrame = this.colorStar[Math.floor(Math.random()*10000)%6];
                        this.background.addChild(star);
                        var x = Math.floor(Math.random()*10000)%640 - 320;
                        var y = Math.floor(Math.random()*10000)%1136 - 568;
                        var seqStar = cc.sequence(cc.moveTo(1,cc.v2(x,y)),cc.removeSelf());
                        star.runAction(seqStar);
                    }
                    cc.audioEngine.play(this.pop,false,1);
                    this.dataArray[data.data].destroy();
                    this.dataArray[data.data] = null;
                }.bind(this),this,{data:i})));
            }

            else if(obj.flag == "move" && obj.length > 0)
            {
                moveArr.push({id:i,length:obj.length});
            }
        }


       
        this.scheduleOnce(function(){
            for(var i = 0;i<moveArr.length;i++)
            {
                var item = moveArr[i];
                var x = this.dataArray[item.id].position.x;
                var y = this.dataArray[item.id].position.y - this.size.width/10 *item.length;
                var act = cc.moveTo(0.3,cc.v2(x,y));
                this.dataArray[item.id].runAction(act);
                this.dataArray[item.id].yy -= item.length;
            }

             //控制 左移逻辑
            var empty_lieArray = [];
            for(var x = 0;x < 10;x++)
            {
                var isContantBox = false;
                for(var i = 0;i<this.dataArray.length;i++)
                {
                    var box = this.dataArray[i];
                    if(box == null) continue;
                    if(box.xx == x){
                        isContantBox = true;
                        break;
                    }
                }
                if(isContantBox == false)
                {
                    empty_lieArray.push(x);
                }
            }
            console.log(empty_lieArray);
            var array = this.leftMoveInfos(empty_lieArray);
            if(array.length >= 0){
                for(var i=0;i<array.length;i++)
                {
                    var id = array[i].id;
                    var length = array[i].length;
                    var x = this.dataArray[id].position.x - this.size.width/10*length;
                    var y = this.dataArray[id].position.y;
                    var act = cc.moveTo(0.2,cc.v2(x,y));
                    this.dataArray[id].runAction(act);
                    this.dataArray[id].xx -= length;
                }
            } 
        }.bind(this),++h*0.1);
        
        //判断界面中是否还有可消除项
        this.scheduleOnce(function(){
            this.isxiaochuzhong = false;
            this.checkBox();  //检测界面上是否还有可以消除元素    
        }.bind(this),0.5);
       

    },

    /* 检测界面上是否还有可以消除元素 */
    checkBox(){
        var isHaveCanXCX = false; 
        for(var i=0;i<this.dataArray.length;i++)
        {
            var box = this.dataArray[i];
            if(box == null) continue;

            this.selectColorBoxs = [box];
            this.bianliArray = [box];
            this.getAround(this.bianliArray);
            if(this.selectColorBoxs.length >1){
                isHaveCanXCX = true;
                break;
            }
        }
        if(isHaveCanXCX == false)
        {
            var j = 0;
            for(var i=0;i<this.dataArray.length;i++)
            {
                var box = this.dataArray[i];
                if(box == null) continue;
                ++j;
                box.runAction(cc.sequence(cc.delayTime(0.1*j),cc.callFunc(function (target,data) {
                    for(var z=0;z<4;z++){
                        var star = cc.instantiate(this.gameStar);
                        star.position = this.dataArray[data.data].position;
                        star.getComponent(cc.Sprite).spriteFrame = this.colorStar[Math.floor(Math.random()*10000)%6];
                        this.background.addChild(star);
                        var x = Math.floor(Math.random()*10000)%640 - 320;
                        var y = Math.floor(Math.random()*10000)%1136 - 568;
                        var seqStar = cc.sequence(cc.moveTo(1,cc.v2(x,y)),cc.removeSelf());
                        star.runAction(seqStar);
                    }
                    cc.audioEngine.play(this.pop,false,1);
                    this.dataArray[data.data].destroy();

                }.bind(this),this,{data:i})));
            }

             //判断界面中是否还有可消除项
            this.scheduleOnce(function(){
                var score = 0;
                switch (j)
                {
                    case 0:{ score = 2000;break}
                    case 1:{ score = 1800;break}
                    case 2:{ score = 1500;break}
                    case 3:{ score = 1200;break}
                    case 4:{ score = 1000;break}
                    case 5:{ score = 800;break}
                    case 6:{ score = 600;break}
                    case 7:{ score = 400;break}
                    case 8:{ score = 200;break}
                    case 9:{ score = 100;break}
                    case 10:{ score = 50;break}
                    default:
                        score = 10;
                }
                this.addCount = Math.ceil(score/20);
                this.resultNode.active = true;
                this.resultLabel.string = "剩余"+j+"个糖果"+'\n'+'\n'+"奖励"+score+"分";
                this.targetScore += score;
                this.resultNode.setScale(0.2,0.2);
                this.resultNode.runAction(cc.scaleTo(0.5,1,1));


                var getScoreLab = new cc.Node('getScoreLab');
                const label = getScoreLab.addComponent(cc.Label);
                label.string = "" + score;
                label.fontSize = 60;
                label.lineHeight = 60;
                getScoreLab.position = cc.v2(60,200);
                getScoreLab.width = 200;
                getScoreLab.height = 80;
                this.background.addChild(getScoreLab);
                var seq = cc.sequence(cc.moveTo(0.8,cc.v2(60,400)),cc.removeSelf());
                getScoreLab.runAction(seq);
            }.bind(this),1);
        }
        else
        {
            console.log("有可以消除想");
        }
    },


    getActionInfos(box,allX)
    {
        var isInMoveLie = false;
        for(var i=0;i<allX.length;i++)
        {
            var itm = allX[i];
            if(itm == box.xx){
                isInMoveLie = true;
                break;
            }
        }
        if(isInMoveLie == false)
        {
            return {flag:"not_move",length:0}
        }

        var moveLength = 0;
        for(var i=0;i<this.selectColorBoxs.length;i++){
            var item = this.selectColorBoxs[i];
            if(item.xx == box.xx && item.yy<box.yy){
                ++moveLength;
            }
            else if(item.xx == box.xx && item.yy==box.yy){
                return {flag:"destory",length:0};        
            }
        }
        return {flag:"move",length:moveLength};
    },
   
    /* 向左移动数据表 */
    leftMoveInfos(empty_lieArray){
        if(empty_lieArray.length == 0) return [];
        
        var array = [];

        for(var i = 0;i<this.dataArray.length;i++)
        {
            var box = this.dataArray[i];
            if(box == null) continue;

            var moveLength = 0;
            for(var j=0;j<empty_lieArray.length;j++)
            {
                var k = empty_lieArray[j];
                if(box.xx > k)
                {
                    ++moveLength;
                }
            }
            if(moveLength > 0)
            {
                array.push({id :i,length:moveLength});
            }
        }
        return array;
    },

     update (dt) {
        var score = parseInt(this.scoreLab.string);
        if(score != this.targetScore && ++this.counter % 5 == 0){
            if(score < this.targetScore)
            {
                this.scoreLab.string = ""+(score+this.addCount);
            } 
            else{
                this.scoreLab.string = ""+this.targetScore;
            }
        }

        //清零防止溢出
        if(this.counter == 50000) this.counter = 0;
     },
     closeReward(){
        this.resultNode.active = false;
        this.initData();

     },
});
